package com.system.jfm.MainTables;

import com.system.Daos.AdminDao;
import com.system.Models.Admin;
import com.system.jfm.Components.LabelPasswordTextField;
import com.system.jfm.Components.Message;
import com.system.tools.MyFunction;
import com.system.jfm.LoginFrame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

public class ChangeAdminPassword extends JPanel {

    LabelPasswordTextField oldPwd;
    LabelPasswordTextField newPwd;
    LabelPasswordTextField confirmPwd;
    JLabel label;
    Admin admin;
    JButton confirm_btn;
    public ChangeAdminPassword(Admin admin, MyFunction closeFunction) throws SQLException {
        this.admin=admin;
        JPanel p = this;

        label=new JLabel("           更改密码");

       oldPwd= new LabelPasswordTextField("旧密码",200,30,0.3);
       newPwd =new LabelPasswordTextField("新密码",200,30,0.3);
       confirmPwd=  new LabelPasswordTextField("确认密码",200,30,0.3);
       confirm_btn=new JButton("确认");
       confirm_btn.setFont(new Font("微软雅黑",Font.BOLD,12));
       label.setFont(new Font("微软雅黑",Font.BOLD,20));
       this.setPreferredSize(new Dimension(400,300));
        label.setPreferredSize(new Dimension(200,150));
        oldPwd.setPreferredSize(new Dimension(200,30));
        newPwd.setPreferredSize(new Dimension(200,30));
        confirmPwd.setPreferredSize(new Dimension(200,30));
        confirm_btn.setPreferredSize(new Dimension(200,30));

        confirm_btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if ((!oldPwd.getText().equals("")) && (!newPwd.getText().equals("")) && (!confirmPwd.getText().equals(""))) {
                    boolean flag=false;
                    if (newPwd.getText().equals(confirmPwd.getText())) {
                        try {
                             flag = new AdminDao(new Admin(admin.getName(),oldPwd.getText())).changePassword(newPwd.getText());
                        } catch (SQLException ex) {
                            throw new RuntimeException(ex);
                        }
                        if (flag){
                            new Message("密码修改成功");
                            try {
                                closeFunction.exec();
                            } catch (SQLException ex) {
                                throw new RuntimeException(ex);
                            }
                            new LoginFrame();
                        }
                    } else {
                        new Message("确认密码与新密码不一致");
                    }
                }else {
                    new Message("不能为空");
                }
            }
        });

        this.add(label);
        this.add(oldPwd);
        this.add(newPwd);
        this.add(confirmPwd);
        this.add(confirm_btn);

    }

}
